from flask import Flask, request
from flask_cors import CORS
import subprocess
import os

app = Flask(__name__)
CORS(app)

@app.route('/upload', methods=['POST', 'GET'])
def handle_upload():
    if request.method == 'POST':
        # 获取上传的文件对象
        file = request.files['file']
        if not file:
            return 'File is missing.', 400
        try:
            # 保存文件到本地
            file.save(os.path.join('data/', file.filename))
            fileObject = open('data/filename.txt','w')
            fileObject.write('data/'+file.filename)
            return 'File uploaded successfully.'
        except Exception as e:
            return str(e), 500
    else:
        return 'Welcome to the home page!', 200

@app.route('/execute_sensitivity_division', methods=['POST', 'GET'])
def handle_sensitivity_division():
    subprocess.run(['python', 'Function/Sensitivity_division.py'])
    return "execute_sensitivity_division clicked!"

@app.route('/encrypted_LS', methods=['POST', 'GET'])
def handle_encrypted_LS():
    subprocess.run(['python', 'Function/encrypted_LS.py'])
    return "encrypted_LS clicked!"

@app.route('/encrypted_HS', methods=['POST', 'GET'])
def handle_encrypted_HS():
    subprocess.run(['python', 'Function/encrypted_HS.py'])
    return "encrypted_HS clicked!"

@app.route('/decrypted_LS', methods=['POST', 'GET'])
def handle_decrypted_LS():
    subprocess.run(['python', 'Function/decrypted_LS.py'])
    return "decrypted_LS clicked!"

@app.route('/decrypted_HS', methods=['POST', 'GET'])
def handle_decrypted_HS():
    subprocess.run(['python', 'Function/decrypted_HS.py'])
    return "decrypted_HS clicked!"


@app.route('/upload-file-and-string', methods=['POST', 'GET'])
def upload_file_and_string():
    if request.method == 'POST':
        if 'file' not in request.files:
            return '文件未上传'

        file = request.files['file']
        if file.filename == '':
            return '未选择文件'

        try:
            file.save(os.path.join('data/', 'HospitalUpload.csv'))

            if 'KeyValue' not in request.form:
                return '字符串值未提供'

            string_value = request.form['KeyValue']
            print('接收到的字符串值:', string_value)
            with open('value/Hospital_Upload_key.key', 'w') as hash_file:
                hash_file.write(f'{string_value}')
            # 在这里进行字符串值的处理或其他操作

            return '文件和字符串值上传成功'

        except Exception as e:
            return str(e), 500

if __name__ == '__main__':
    app.run()